<template>
  <view class="login-page">
    <!-- 标题区域 -->
    <view class="login-title">账号登录</view>

    <!-- 登录方式选择：授权/手动输入 -->
    <!-- <view class="phone-method-switch">
      <view
        class="method-item"
        :class="{ active: phoneMethod === 'auth' }"
        @click="switchPhoneMethod('auth')"
      >
        快捷登录（授权手机号）
      </view>
      <view
        class="method-item"
        :class="{ active: phoneMethod === 'manual' }"
        @click="switchPhoneMethod('manual')"
      >
        手动输入手机号
      </view>
    </view> -->

    <!-- 授权获取手机号区域 -->
    <view class="phone-area" v-if="phoneMethod === 'auth'">
      <button
        class="auth-btn"
        open-type="getPhoneNumber"
        @getphonenumber="onGetPhoneNumber"
        v-if="!authPhoneNumber"
      >
        <text class="auth-text">授权获取手机号</text>
      </button>

      <!-- 已获取手机号显示及切换按钮 -->
      <view class="phone-display" v-if="authPhoneNumber">
        <text>已获取手机号：{{ authPhoneNumber }}</text>
        <button class="change-phone-btn" @click="clearAuthPhone">
          更换手机号
        </button>
      </view>
    </view>

    <!-- 手动输入账号区域 -->
    <view class="phone-input-area" v-if="phoneMethod === 'manual'">
      <view class="input-item">
        <input
          type="text"
          placeholder="请输入手机号或邮箱"
          v-model="manualInput"
          class="input-content"
          maxlength="50"
          @input="onAccountInput"
        />
      </view>
    </view>

    <!-- 登录方式切换：密码/验证码（仅手机号时显示） -->
    <view class="login-type-switch" v-if="showLoginTypeSwitch">
      <view
        class="type-item"
        :class="{ active: loginType === 'password' }"
        @click="loginType = 'password'"
      >
        密码登录
      </view>
      <view
        class="type-item"
        :class="{ active: loginType === 'code' }"
        @click="loginType = 'code'"
      >
        验证码登录
      </view>
    </view>

    <!-- 密码输入框 -->
    <view class="input-group" v-if="loginType === 'password' || isEmailLogin">
      <view class="input-item">
        <input
          type="password"
          :placeholder="isEmailLogin ? '请输入邮箱密码' : '请输入密码'"
          v-model="password"
          class="input-content"
        />
      </view>
    </view>

    <!-- 验证码输入框及获取按钮（仅手机号时显示） -->
    <view class="input-group" v-if="loginType === 'code' && !isEmailLogin">
      <view class="input-item code-item">
        <input
          type="number"
          placeholder="请输入验证码"
          v-model="code"
          class="input-content code-input"
          maxlength="6"
        />
        <button
          class="get-code-btn"
          @click="getVerificationCode"
          :disabled="countdown > 0 || !isPhoneAvailable"
        >
          {{ countdown > 0 ? `${countdown}s后重新获取` : "获取验证码" }}
        </button>
      </view>
    </view>

    <!-- 登录按钮 -->
    <button
      class="login-btn"
      @click="handleLogin"
      :disabled="!isFormValid"
    >
      {{ loginButtonText }}
    </button>

    <!-- 其他选项 -->
    <view class="login-options">
      <button class="login-link" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
        还没有账号? 点此快捷登录
      </button>
    </view>

    <!-- 当前登录类型提示 -->
    <!-- <view class="login-type-hint" v-if="currentLoginType">
      当前登录方式：{{ currentLoginType }}
    </view> -->
  </view>
</template>

<script>
import http from "@/utils/http.js";
import { sendMsgByPhone, getUserInfo, getWxLoginCode, weixinMiniAppLogin } from "@/api";

export default {
  data() {
    return {
      // 手机号方式：auth-授权获取，manual-手动输入
      phoneMethod: "manual",

      // 授权方式的手机号
      authPhoneNumber: "", // 显示用（中间四位隐藏）
      realAuthPhone: "", // 真实手机号（用于登录）
      encryptedData: "",
      iv: "",

      // 手动输入的账号（手机号或邮箱）
      manualInput: "",

      // 登录方式
      loginType: "password", // password/code

      // 表单数据
      password: "",
      code: "",

      // 验证码倒计时
      countdown: 0,

      // 当前输入类型（自动识别）
      inputType: null, // null-未识别, 'phone'-手机号, 'email'-邮箱
    };
  },
  computed: {
    // 判断是否为邮箱登录
    isEmailLogin() {
      return this.inputType === 'email';
    },

    // 判断是否为手机号登录
    isPhoneLogin() {
      return this.inputType === 'phone' || this.phoneMethod === 'auth';
    },

    // 是否显示登录方式切换（仅手机号登录且非授权方式时显示）
    showLoginTypeSwitch() {
      return this.isPhoneLogin && this.phoneMethod === 'manual';
    },

    // 验证手机号是否可用
    isPhoneAvailable() {
      if (this.phoneMethod === "auth") {
        return !!this.authPhoneNumber;
      } else {
        // 手动输入时验证格式
        const reg = /^1[3-9]\d{9}$/;
        return reg.test(this.manualInput);
      }
    },

    // 验证邮箱是否可用
    isEmailAvailable() {
      const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      return reg.test(this.manualInput);
    },

    // 获取当前有效的手机号（用于登录）
    currentPhone() {
      return this.phoneMethod === "auth"
        ? this.realAuthPhone
        : this.manualInput;
    },

    // 表单验证
    isFormValid() {
      if (this.phoneMethod === "auth") {
        // 授权登录
        return !!this.authPhoneNumber && 
               (this.loginType === 'password' ? !!this.password : !!this.code);
      } else {
        // 手动输入登录
        if (!this.inputType) return false;
        
        if (this.inputType === 'phone') {
          // 手机号登录
          return this.isPhoneAvailable && 
                 (this.loginType === 'password' ? !!this.password : !!this.code);
        } else {
          // 邮箱登录（只支持密码登录）
          return this.isEmailAvailable && !!this.password;
        }
      }
    },

    // 登录按钮文字
    loginButtonText() {
      if (this.isEmailLogin) {
        return "邮箱登录";
      } else if (this.isPhoneLogin) {
        return this.loginType === 'password' ? "密码登录" : "验证码登录";
      }
      return "登录";
    },

    // 当前登录类型提示
    currentLoginType() {
      if (this.phoneMethod === "auth") {
        return "手机号授权登录";
      } else if (this.isEmailLogin) {
        return "邮箱密码登录";
      } else if (this.isPhoneLogin) {
        return this.loginType === 'password' ? "手机号密码登录" : "手机号验证码登录";
      }
      return "";
    }
  },
  methods: {
    // 账号输入变化时识别类型
    onAccountInput() {
      if (!this.manualInput) {
        this.inputType = null;
        return;
      }

      // 优先识别为邮箱
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (emailReg.test(this.manualInput)) {
        this.inputType = 'email';
        // 邮箱登录只支持密码方式
        this.loginType = 'password';
        return;
      }

      // 识别为手机号
      const phoneReg = /^1[3-9]\d{9}$/;
      if (phoneReg.test(this.manualInput)) {
        this.inputType = 'phone';
        return;
      }

      // 无法识别
      this.inputType = null;
    },

    // 微信小程序的"手机号快速验证"
    async getPhoneNumber(e) {
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        return;
      }
      // 1. 调用 wx.login 获取临时登录凭证 code
      const { code }  = await getWxLoginCode();
      // 2. 一键登录
      console.log('getPhoneNumber',e.detail.code);
      const loginResult = await weixinMiniAppLogin(e.detail.code, code, 'default');
      
      if (loginResult) {
        // 登录成功，保存用户信息
        uni.setStorageSync("token", loginResult.accessToken);
        uni.setStorageSync("openid", loginResult.openid);
        this.getUserInfo();
        uni.showToast({
          title: "登录成功",
          icon: "success",
        });
      }
    },

    /**
     * 切换手机号获取方式
     */
    switchPhoneMethod(method) {
      this.phoneMethod = method;
      // 切换时清空相关数据
      this.password = "";
      this.code = "";
      if (this.countdown > 0) {
        this.countdown = 0;
      }
    },

    /**
     * 处理手机号授权
     */
    onGetPhoneNumber(e) {
      // 拒绝授权
      if (e.detail.errMsg === "getPhoneNumber:fail user deny") {
        uni.showToast({
          title: "请授权手机号才能登录",
          icon: "none",
        });
        return;
      }

      // 同意授权，保存加密数据
      this.encryptedData = e.detail.encryptedData;
      this.iv = e.detail.iv;

      // 解密手机号（实际项目中需要后端解密）
      this.decryptPhoneNumber();
    },

    /**
     * 解密手机号
     */
    decryptPhoneNumber() {
      http({
        url: "/api/decrypt-phone",
        method: "POST",
        data: {
          encryptedData: this.encryptedData,
          iv: this.iv,
          sessionKey: uni.getStorageSync("sessionKey"),
        },
      })
        .then((res) => {
          // 保存真实手机号（用于登录）
          this.realAuthPhone = res.phoneNumber;
          // 显示时隐藏中间四位
          this.authPhoneNumber = res.phoneNumber.replace(
            /(\d{3})(\d{4})(\d{4})/,
            "$1****$3"
          );
          uni.showToast({
            title: "手机号授权成功",
            icon: "none",
          });
        })
        .catch((err) => {
          console.error("解密失败", err);
          uni.showToast({
            title: "获取手机号失败，请重试",
            icon: "none",
          });
        });
    },

    /**
     * 清除已授权的手机号
     */
    clearAuthPhone() {
      this.authPhoneNumber = "";
      this.realAuthPhone = "";
      this.encryptedData = "";
      this.iv = "";
    },

    /**
     * 获取验证码（仅手机号登录可用）
     */
    async getVerificationCode() {
      if (!this.isPhoneAvailable) {
        uni.showToast({
          title:
            this.phoneMethod === "auth"
              ? "请先授权手机号"
              : "请输入正确的手机号",
          icon: "none",
        });
        return;
      }
      let res = await sendMsgByPhone({
        mobile: this.currentPhone,
        scene: 1,
      });
      if (res) {
        uni.showToast({
          title: "验证码发送成功",
          icon: "none",
        });

        // 开始倒计时
        this.countdown = 60;
        const timer = setInterval(() => {
          this.countdown--;
          if (this.countdown <= 0) {
            clearInterval(timer);
          }
        }, 1000);
      }
    },

    /**
     * 处理登录
     */
    async handleLogin() {
      if (!this.isFormValid) {
        let message = '';
        if (this.phoneMethod === 'auth') {
          message = '请先授权手机号';
        } else if (this.inputType === 'phone') {
          message = '请输入正确的手机号' + (this.loginType === 'password' ? '和密码' : '和验证码');
        } else if (this.inputType === 'email') {
          message = '请输入正确的邮箱和密码';
        } else {
          message = '请输入正确的手机号或邮箱';
        }
        uni.showToast({
          title: message,
          icon: "none",
        });
        return;
      }

      // 准备登录参数
      const loginParams = {};

      let url = "";
      
      if (this.isEmailLogin) {
        // 邮箱登录
        loginParams.mail = this.manualInput;
        loginParams.password = this.password;
        url = "/app-api/member/auth/mail-login"; // 假设邮箱登录接口
      } else {
        // 手机号登录
        loginParams.mobile = this.currentPhone;
        
        if (this.loginType === "password") {
          loginParams.password = this.password;
          loginParams.socialCodeValid = false;
          url = "/app-api/member/auth/login";
        } else {
          loginParams.code = this.code;
          url = "/app-api/member/auth/sms-login";
        }
      }

      // 微信登录相关参数（可选）
      try {
        const { code } = await getWxLoginCode();
        console.log('code=====>' + code);
        if (code) {
          loginParams.socialType = 34; // 社交登录-小程序
          loginParams.socialCode = code;
          loginParams.socialState = Date.now() + Math.random().toString(36).substr(2);
        }
      } catch (error) {
        console.log('获取微信登录code失败，继续普通登录');
      }

      // 调用登录接口
      http({
        url,
        method: "POST",
        data: loginParams,
      })
        .then((res) => {
          // 登录成功，保存用户信息
          uni.setStorageSync("token", res.accessToken);
          uni.setStorageSync("openid", res.openid);
          this.getUserInfo();
          uni.showToast({
            title: "登录成功",
            icon: "success",
          });
        })
        .catch((err) => {
          console.error("登录失败", err);
          uni.showToast({
            title: err.msg || "登录失败，请重试",
            icon: "none",
          });
        });
    },

    async getUserInfo() {
      // 跳转到首页
      setTimeout(() => {
        uni.switchTab({
          url: "/pages/my/my",
        });
      }, 1500);
    },
  },
};
</script>

<style lang="less" scoped>
.login-page {
  display: flex;
  flex-direction: column;
  padding: 60rpx 40rpx;
  background-color: #f5f5f5;
  min-height: 100vh;

  .login-title {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 40rpx;
  }

  /* 手机号获取方式切换 */
  .phone-method-switch {
    display: flex;
    width: 100%;
    height: 80rpx;
    border-radius: 40rpx;
    background-color: #eee;
    margin-bottom: 40rpx;
    overflow: hidden;

    .method-item {
      flex: 1;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      padding: 0 10rpx;
      text-align: center;
      transition: all 0.3s;

      &.active {
        background-color: #2b88e6;
        color: #fff;
      }
    }
  }

  /* 授权手机号区域 */
  .phone-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 40rpx;

    .auth-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 90rpx;
      background-color: #2b88e6;
      color: #fff;
      border-radius: 45rpx;
      font-size: 32rpx;

      .phone-icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 15rpx;
      }
    }

    .phone-display {
      display: flex;
      align-items: center;
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #666;

      .change-phone-btn {
        margin-left: 20rpx;
        background-color: transparent;
        color: #2b88e6;
        font-size: 26rpx;
        padding: 0 10rpx;
        height: auto;
        line-height: normal;
      }
    }
  }

  /* 手动输入手机号区域 */
  .phone-input-area {
    width: 100%;
    margin-bottom: 40rpx;
  }

  /* 通用输入框样式 */
  .input-item {
    display: flex;
    align-items: center;
    height: 90rpx;
    background-color: #fff;
    border-radius: 10rpx;
    padding: 0 30rpx;
    margin-bottom: 20rpx;

    .input-icon {
      width: 36rpx;
      height: 36rpx;
      margin-right: 20rpx;
    }

    .input-content {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
    }
  }

  /* 登录方式切换 */
  .login-type-switch {
    display: flex;
    width: 100%;
    height: 80rpx;
    border-radius: 40rpx;
    background-color: #eee;
    margin-bottom: 40rpx;

    .type-item {
      flex: 1;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      border-radius: 40rpx;
      transition: all 0.3s;

      &.active {
        background-color: #2b88e6;
        color: #fff;
      }
    }
  }

  /* 验证码区域 */
  .input-group {
    width: 100%;
    margin-bottom: 60rpx;

    .code-item {
      position: relative;

      .code-input {
        padding-right: 220rpx;
      }

      .get-code-btn {
        position: absolute;
        right: 10rpx;
        top: 50%;
        transform: translateY(-50%);
        width: 200rpx;
        height: 60rpx;
        line-height: 60rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        border-radius: 30rpx;

        &:disabled {
          background-color: #ddd;
          color: #999;
        }
      }
    }
  }

  /* 登录按钮 */
  .login-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background-color: #2b88e6;
    color: #fff;
    border-radius: 45rpx;
    font-size: 32rpx;
    margin-bottom: 40rpx;

     &[disabled]{
      background-color: #99c9ff;
      color: #fff 
    }
  }

  /* 其他选项 */
  .login-options {
    display: flex;
    justify-content: flex-end;
    font-size: 26rpx;

    .forgot-link,
    .register-link {
      color: #2b88e6;
      text-decoration: none;
    }
	
	/* 统一所有链接/按钮的样式 */
	  .login-link {
		color: #2b88e6; /* 与原有链接颜色一致 */
		text-decoration: none; /* 去除下划线 */
		font-size: 26rpx; /* 与原有字体大小一致 */
		line-height: 1; /* 行高紧凑 */
		padding: 0; /* 去除内边距 */
		margin: 0; /* 去除外边距 */

		/* 针对按钮的特殊样式重置 */
		&:last-child { /* 仅最后一个元素（快捷登录按钮）需要 */
		  background: none; /* 去除按钮默认背景 */
		  border: none; /* 去除按钮默认边框 */
		  border-radius: 0; /* 去除按钮默认圆角 */
		  outline: none; /* 去除聚焦时的外框 */
		  
		  /* 修复部分平台按钮默认字体加粗问题 */
		  font-weight: normal;
		}
	  }
  }
}
</style>
    